define(['jquery','mui', 'validator', 'validator-lang','swiper'], function ($, $$,Validator, undefined, Swiper) {
    var Form = {
        config: {
            fieldlisttpl: '<dd class="form-inline"><input type="text" name="<%=name%>[<%=index%>][key]" class="form-control" value="<%=row.key%>" size="10" /> <input type="text" name="<%=name%>[<%=index%>][value]" class="form-control" value="<%=row.value%>" /> <span class="btn btn-sm btn-danger btn-remove"><i class="fa fa-times"></i></span> <span class="btn btn-sm btn-primary btn-dragsort"><i class="fa fa-arrows"></i></span></dd>',
            maxCount: 1,
            allowTypes: [ 'image/jpg', 'image/jpeg', 'image/png', 'image/gif' ],
            // 1024KB，也就是 1MB
             maxSize: 1024 * 1024,
            // 图片最大宽度
            maxWidth: 800,
            maxHeight: 800,
            readonly: false,
            imgLimit: false,
            myswiper: null,
            totalimglist: 0
            // 最大上传图片数量
        },
        events: {
            validator: function (form, success, error, submit) {
                if (!form.is("form"))
                    return;


                //绑定表单事件
                form.validator($.extend({

                    display: function (elem) {
                        // var tip=  $(elem).closest('.mui-input-row').find("label").text().replace(/\:/, '');
                        // console.log(tip);
                        // console.log(elem)
                        // var tip = $(elem).attr('placeholder');
                        // console.log(tip)
                        // return tip;
                    },
                    dataFilter: function (data) {
                        if (data.code === 1) {
                            return data.msg ? {"ok": data.msg} : '';
                        } else {
                            return data.msg;
                        }
                    },
                    invalid:function(form, errors){
                        // console.log(errors);
                        if(errors.length>0)
                        {
                            showTips(errors[0]);
                            // $$.alert(errors[0]);
                        }else
                            hideTips();
                    },
                    target: function(elem){
                        var $formitem = $(elem).closest('.form-item'),
                            $msgbox = $formitem.find('span.msg-box');
                        if (!$msgbox.length) {
                            $msgbox = $('<span class="msg-box"></span>').appendTo($formitem);
                        }
                        return $msgbox;
                    },
                    valid: function (ret) {
                        var that = this, submitBtn = $(".layer-footer [type=submit]", form);
                        that.holdSubmit(true);
                        submitBtn.addClass("disabled");
                        //验证通过提交表单
                        var submitResult = Form.api.submit($(ret), function (data, ret) {
                            console.log(ret)
                            that.holdSubmit(false);
                            submitBtn.removeClass("disabled");
                            if (false === $(this).triggerHandler("success.form", [data, ret])) {
                                return false;
                            }
                            if (typeof success === 'function') {
                                if (false === success.call($(this), data, ret)) {
                                    return false;
                                }
                            }
                            $$.alert(ret.msg,function(){
                                if(ret.url)
                                    window.location.href = ret.url
                            })
                            return false;
                        }, function (data, ret) {
                            $$.alert(ret.msg);
                            that.holdSubmit(false);
                            if (false === $(this).triggerHandler("error.form", [data, ret])) {
                                return false;
                            }
                            submitBtn.removeClass("disabled");
                            if (typeof error === 'function') {
                                if (false === error.call($(this), data, ret)) {
                                    return false;
                                }
                            }

                        }, submit);
                        //如果提交失败则释放锁定
                        // console.log(submitResult)
                        if (!submitResult) {
                            that.holdSubmit(false);
                            submitBtn.removeClass("disabled");
                        }
                        return false;
                    }
                }, form.data("validator-options") || {}));

                //移除提交按钮的disabled类
                $(".layer-footer [type=submit],.fixed-footer [type=submit],.normal-footer [type=submit]", form).removeClass("mui-disabled");
                //自定义关闭按钮事件

            },
            bindevent: function (form) {
                form.on('validation', function(e, current){

                    // var form = this;
                    // form 中是否所有字段都验证通过
                    // console.log(form.isValid);
                    // console.log(current.element);
                    // console.log(current.value);
                    // console.log(current.msg);

                    // 当前验证字段是否通过
                    var isValid = current.isValid;

                    if(isValid)
                        hideTips();
                    else
                        showTips(current.msg)
                });


            },
            dtpicker: function (form) {
                //绑定日期时间元素事件
                $(".dtpicker").click(function(event) {
                    var _self = this;
                    var options = $(this).data('options');
                    _self.picker = new $$.DtPicker(options);
                    _self.picker.show(function(rs) {
                       $(_self).val(rs.text)
                        _self.picker.dispose();
                        _self.picker = null;
                    });
                });
            },
            temppicker: function (form) {
                //绑定日期时间元素事件
                // var tempPicker = new $$.PopPicker({
                //     layer:2,
                //     noLink: true
                // });
                // tempPicker.setData([[{
                //     value: '36',
                //     text: '36'
                // }, {
                //     value: '37',
                //     text: '37'
                // }, {
                //     value: '38',
                //     text: '38'
                // }, {
                //     value: '39',
                //     text: '39'
                // }, {
                //     value: '40',
                //     text: '40'
                // }, {
                //     value: '41',
                //     text: '41'
                // }, {
                //     value: '42',
                //     text: '42'
                // }],[
                //     {value: '0',text:'0'},
                //     {value: '1',text:'1'},
                //     {value: '2',text:'2'},
                //     {value: '3',text:'3'},
                //     {value: '4',text:'4'},
                //     {value: '5',text:'5'},
                //     {value: '6',text:'6'},
                //     {value: '7',text:'7'},
                //     {value: '8',text:'8'},
                //     {value: '9',text:'9'},
                // ]]);

                // $(".temppicker").click(function(event) {
                //     var _self = this;
                //     tempPicker.show(function(items) {
                //         value = items[0].value  +"." + items[1].value
                //         $(_self).val(value);
                //         // userResult.innerText = JSON.stringify(items[0]);
                //         //返回 false 可以阻止选择框的关闭
                //         //return false;
                //     });

                // });
            },
            upload: function(form) {
                var allowTypes = Form.config.allowTypes;
                // 1024KB，也就是 1MB
                var maxSize = Form.config.maxSize;
                // 图片最大宽度
                var maxWidth = Form.config.maxWidth;
                var maxHeight = Form.config.maxHeight;
                // 最大上传图片数量
                var maxCount = Form.config.maxCount;

                var tmpl = '<li class="mui-uploader__file mui-uploader__file_status" id="#ImgID#" style="background-image:url(#url#)"> <div class="mui-uploader__file-content"></div></li>',
                    $gallery = $("#gallery"),
                    $galleryImg = $("#galleryImg"),
                    $uploaderInput = $(".pupload"),
                    $uploaderFiles = $("#uploaderFiles"),
                    $galleryDelete=$(".mui-gallery__opr"),
                    $previewer=$(".previewer"),
                    element = $(".pupload"),
                    swiperElement = $(".swiper-wrapper");


                var u = navigator.userAgent;
                if(u.indexOf('Android') > -1 || u.indexOf('Adr') > -1)
                {

                    $("#uploaderInput").attr('capture','camera');
                }
                element.each(function () {
                    var that = this;
                    var input_id = $(that).data("input-id") ? $(that).data("input-id") : "";
                    var preview_id = $(that).data("preview-id") ? $(that).data("preview-id") : "";
                    var multiple = $(that).attr('multiple');
                    var max = $(that).data('max')?$(that).data('max'):maxCount;
                    var readonly = $(that).data('readonly')?$(that).data('max'):Form.config.readonly;
                    var imgLimit = $(that).data('imglimit')?$(that).data('imglimit'):Form.config.imgLimit;
                    var images_count = 0;
                    var input_box = $(that).parent(".mui-uploader__input-box");

                    $(this).on("change", function(event){
                        var src, url = window.URL || window.webkitURL || window.mozURL, files = event.target.files;
                        if (files.length === 0) {
                            return;
                        }
                        for (var i = 0, len = files.length; i < len; ++i) {
                            var fd = new FormData();
                            fd.append('file', files[i]);
                            $.ajax({
                                url:'/wap/ajax/upload',
                                type:'POST',
                                data:fd,
                                processData:false,  //tell jQuery not to process the data
                                contentType: false,  //tell jQuery not to set contentType
                                //这儿的三个参数其实就是XMLHttpRequest里面带的信息。
                                success:function (ret) {
                                    if(ret.code == 1 )
                                    {
                                        var data = typeof ret.data !== 'undefined' ? ret.data : null;
                                        if (input_id) {
                                            var urlArr = [];
                                            var inputObj = $("#" + input_id);
                                            if (multiple && inputObj.val() !== "") {
                                                console.log(inputObj.val())
                                                urlArr.push(inputObj.val());
                                            }
                                            urlArr.push(data.url);

                                            // inputObj.val(urlArr.join(","));
                                            inputObj.val(urlArr.join(",")).trigger("change");
                                        }
                                    }
                                }
                            })
                        }
                    })


                    if (preview_id && input_id) {
                        $(document.body).on("keyup change", "#" + input_id, function (e) {
                            var inputStr = $("#" + input_id).val();
                            var inputArr = inputStr.split(/\,/);
                            $("#" + preview_id).empty();
                            var tpl = $("#" + preview_id).data("template") ? $("#" + preview_id).data("template") : "";
                            images_count = 0;

                            $.each(inputArr, function (i, j) {
                                if (!j) {
                                    return true;
                                }
                                images_count++;

                                // var suffix = /[\.]?([a-zA-Z0-9]+)$/.exec(j);
                                // suffix = suffix ? suffix[1] : 'file';
                                // var data = {url: j, fullurl: Fast.api.cdnurl(j), data: $(that).data(), key: i, index: i, value: (json && typeof json[i] !== 'undefined' ? json[i] : null), suffix: suffix};
                                // var html = tpl ? Template(tpl, data) : Template.render(Upload.config.previewtpl, data);
                                var html = $('<li class="mui-uploader__file" data-url="'+j+'"  id="ImgID" style="background-image:url(' + j + ')"></li>');
                                var galleryhtml = $('<div class="swiper-slide"><span class="mui-gallery__img" id="'+input_id +'-'+i+'" style="background-image:url(' + j + ')"></span></div>')
                                $("#" + preview_id).append(html);
                                swiperElement.append(galleryhtml);

                            });

                            if(!readonly && imgLimit && images_count == max){
                                input_box.hide();
                            }
                            else
                                input_box.show();
                        });
                        $("#" + input_id).trigger("change");
                    }
                    if (preview_id) {

                        // 监听事件
                        $(document.body).on("fa.preview.change", "#" + preview_id, function () {
                            var urlArr = [];
                            images_count = 0;
                            $("#" + preview_id + " [data-url]").each(function (i, j) {
                                urlArr.push($(this).data("url"));
                                images_count++;
                            });
                            if (input_id) {
                                $("#" + input_id).val(urlArr.join(","));
                            }

                            if(!readonly && imgLimit && images_count == max){
                                input_box.hide();
                            }
                            else
                                input_box.show();
                            // refresh($("#" + preview_id).data("name"));
                        });


                    }


                })
                form.on("click", "li", function(){
                    index = $(this).index();
                    console.log(index)
                    Form.config.myswiper.slideTo(index);
                    // $galleryImg.data("preview_id", preview_id);
                    // $galleryImg.data("li_index", index);

                    // $galleryImg.attr("style", this.getAttribute("style"));
                    $galleryDelete.show();
                    $gallery.fadeIn(100);
                });
                $(".mui-gallery__del").click(function() {
                    var pre_id = $galleryImg.data("preview_id");
                    var index = $galleryImg.data("li_index")
                    // console.log(index)
                    $('#'+pre_id+' li').eq(index).remove()
                    $("#" + pre_id).trigger("fa.preview.change");
                    // console.log($galleryImg.data("preview_id"));
                })



                var index;

                $previewer.on("click", "li", function(){
                    index = $(this).index();
                    $galleryImg.attr("style", this.getAttribute("style"));
                    $galleryDelete.hide();
                    $gallery.fadeIn(100);
                });

                $gallery.on("click", function(){
                    $gallery.fadeOut(100);
                });
            },
            swiper: function() {
                Form.config.myswiper = new Swiper('.swiper-container');
            }
        },
        api: {
            submit: function (form, success, error, submit) {
                if (form.size() === 0) {
                    $$.alert("表单未初始化完成,无法提交");
                    return false;
                }
                if (typeof submit === 'function') {
                    if (false === submit.call(form, success, error)) {
                        return false;
                    }
                }
                var type = form.attr("method") ? form.attr("method").toUpperCase() : 'GET';
                type = type && (type === 'GET' || type === 'POST') ? type : 'GET';
                url = form.attr("action");
                url = url ? url : location.href;
                //修复当存在多选项元素时提交的BUG
                var params = {};
                var multipleList = $("[name$='[]']", form);
                if (multipleList.size() > 0) {
                    var postFields = form.serializeArray().map(function (obj) {
                        return $(obj).prop("name");
                    });
                    $.each(multipleList, function (i, j) {
                        if (postFields.indexOf($(this).prop("name")) < 0) {
                            params[$(this).prop("name")] = '';
                        }
                    });
                }
                //调用Ajax请求方法
                //
                Fast.api.ajax({
                    type: type,
                    url: url,
                    data: form.serialize() + (Object.keys(params).length > 0 ? '&' + $.param(params) : ''),
                    dataType: 'json',
                    complete: function (xhr) {
                        var token = xhr.getResponseHeader('__token__');
                        if (token) {
                            $("input[name='__token__']").val(token);
                        }
                    }
                }, function (data, ret) {

                    $('.form-group', form).removeClass('has-feedback has-success has-error');
                    if (data && typeof data === 'object') {
                        //刷新客户端token
                        if (typeof data.token !== 'undefined') {
                            $("input[name='__token__']").val(data.token);
                        }
                        //调用客户端事件
                        if (typeof data.callback !== 'undefined' && typeof data.callback === 'function') {
                            data.callback.call(form, data);
                        }
                    }
                    if (typeof success === 'function') {
                        if (false === success.call(form, data, ret)) {
                            return false;
                        }
                    }
                }, function (data, ret) {
                    if (data && typeof data === 'object' && typeof data.token !== 'undefined') {
                        $("input[name='__token__']").val(data.token);
                    }
                    if (typeof error === 'function') {
                        if (false === error.call(form, data, ret)) {
                            return false;
                        }
                    }

                });

                return true;

            },
            bindevent: function (form, success, error, submit) {

                form = typeof form === 'object' ? form : $(form);

                var events = Form.events;

                events.bindevent(form);

                events.validator(form, success, error, submit);
                events.dtpicker(form);
                events.temppicker(form);
                events.upload(form);
                events.swiper();

            },
            custom: {}
        },


    };
    return Form;
});
